import javax.json.bind.JsonbBuilder;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.*;

import com.R1DTO;
import com.R2DTO;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.NameValuePair;

import java.net.InetAddress;
import java.util.List;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import java.util.ArrayList;

import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.util.EntityUtils;
import org.apache.http.HttpEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import javax.json.bind.Jsonb;

@WebServlet(urlPatterns = {"/login/dgut"})
public class LoginServlet extends HttpServlet {

    protected void doGet(HttpServletRequest request,
                         HttpServletResponse response) throws IOException {
        System.out.println("Loginservlet");

        if(request.getParameter("token")==null)
        {

            if(request.getSession().getAttribute("islogin").equals("false")) {
                //继续发起重定向
                try {
                    response.sendRedirect("https://cas.dgut.edu.cn?appid=javaee");
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }else{
                //退出
                System.out.println("退出");
                //向中央认证系统发送登出请求
                request.getSession().setAttribute("islogin","false");
                request.getSession().setAttribute("userid",null);
                request.getSession().invalidate();
                response.sendRedirect("https://cas.dgut.edu.cn/logout?callback=http://localhost:8080/Login.jsp");
            }
        }
        else {
            //获得token了
            System.out.println("获得token了");
            //进行中央系统验证
            //发送带有token参数的http post请求获取返回的json

            String token=request.getParameter("token");
            String appid="javaee";
            String appsecret="b3b52e43ccfd";
            InetAddress inetAddress=InetAddress.getLocalHost();
            String address=inetAddress.getHostAddress();

            CloseableHttpClient httpclient = HttpClients.createDefault();

            final HttpPost httpPost1 = new HttpPost("https://cas.dgut.edu.cn/ssoapi/v2/checkToken");
            //NameValuePair,简单的名称值对节点对象,key:value
            final List<NameValuePair> get1 = new ArrayList<>();
            get1.add(new BasicNameValuePair("token", token));
            get1.add(new BasicNameValuePair("appid", appid));
            get1.add(new BasicNameValuePair("appsecret", appsecret));
            get1.add(new BasicNameValuePair("userip", address));
            httpPost1.setEntity(new UrlEncodedFormEntity(get1));

            try (CloseableHttpResponse response2 = httpclient.execute(httpPost1)) {

                // System.out.println(response2.getCode() + " " + response2.getReasonPhrase());
                final HttpEntity entity2 = response2.getEntity();
                // 必须加utf-8,否则中文乱码
                String jsonstr=EntityUtils.toString(entity2, "UTF-8");
                System.out.println(jsonstr);
                Jsonb jsonb= JsonbBuilder.create();
                R1DTO r1DTO=jsonb.fromJson(jsonstr,R1DTO.class);

                if(r1DTO.getError()!=null&&r1DTO.getError().equals("0"))
                {
                    System.out.println("验证成功");
                    //再次请求用户信息并返回
                    final HttpPost httpPost2=new HttpPost("https://cas.dgut.edu.cn/oauth/getUserInfo");
                    final List<NameValuePair> get2 = new ArrayList<>();
                    get2.add(new BasicNameValuePair("access_token", r1DTO.getAccess_token()));
                    get2.add(new BasicNameValuePair("openid", r1DTO.getOpenid()));
                    httpPost2.setEntity(new UrlEncodedFormEntity(get2));

                    try(CloseableHttpResponse response3=httpclient.execute(httpPost2)){
                        final HttpEntity entity3=response3.getEntity();
                        String jsonstr2=EntityUtils.toString(entity3, "UTF-8");
                        System.out.println(jsonstr2);
                        Jsonb jsonb2=JsonbBuilder.create();
                        R2DTO r2DTO=jsonb2.fromJson(jsonstr2,R2DTO.class);

                        //验证是否接受成功
                        if(r2DTO.getError()==null) {
                            request.getSession().setAttribute("islogin","true");
                            //response.getWriter().println(jsonstr2);
                            request.getSession().setAttribute("jsonstr",jsonstr2);
                            //拿到用户数据后，使用session在servlet与jsp之间传值
                            request.getSession().setAttribute("name",r2DTO.getName());
                            request.getSession().setAttribute("username",r2DTO.getUsername());
                            request.getSession().setAttribute("faculty_title",r2DTO.getFaculty_title());
                            request.getSession().setAttribute("getWx_openid",r2DTO.getWx_openid());
                            //重定向到主页面

                            //两种情况，本地是否已有以userid及密码为123456的数据
                            //1.无，未绑定账号，添加绑定
                            //  若无，新增绑定账号及基本信息，没有填入的信息值为未绑定
                            //  若有，新增绑定账号， 不修改信息值
                            //2.有，直接登录
                            //

                            boolean istp=false;
                            boolean islocal=false;
                            BufferedReader bufferedReader=new BufferedReader(new InputStreamReader(new FileInputStream("Userpwd.txt"),"UTF-8"));
                            while (bufferedReader.ready()){
                                String str=bufferedReader.readLine();
                                String[] parts=str.split(",");
                                if(parts[0].equals(r2DTO.getUsername())&&!parts[2].equals("123456"))
                                    islocal=true;
                                if(parts[0].equals(r2DTO.getUsername())&&parts[2].equals("123456"))
                                    istp=true;
                            }

                            //已有本地账号和绑定账号
//                            if(islocal&&istp){
//                                //直接登录
//                            }

                            //已有本地账号，无绑定账号
                            if(islocal&&!istp){
                                //pwd添加绑定账号
                                OutputStreamWriter outputStreamWriter=new OutputStreamWriter(new FileOutputStream("Userpwd.txt",true),"UTF-8");
                                outputStreamWriter.append(r2DTO.getUsername()+",");
                                outputStreamWriter.append("未绑定,");
                                outputStreamWriter.append("123456\n");
                                outputStreamWriter.close();
                            }

//                            //已有绑定账号，无本地账号
//                            if(!islocal&&istp){
//                                //这里本地账号的注册会有点问题，暂时不改动,直接登录
//                            }

                            //无本地账号，无绑定账号
                            if(!islocal&&!istp){
                                //添加绑定账号和部分基本信息

                                OutputStreamWriter outputStreamWriter1=new OutputStreamWriter(new FileOutputStream("Userpwd.txt",true),"UTF-8");
                                outputStreamWriter1.append(r2DTO.getUsername()+",");
                                outputStreamWriter1.append("未绑定,");
                                outputStreamWriter1.append("123456\n");
                                outputStreamWriter1.close();

                                OutputStreamWriter outputStreamWriter2=new OutputStreamWriter(new FileOutputStream("User.txt",true),"UTF-8");
                                outputStreamWriter2.append(r2DTO.getUsername()+",");
                                outputStreamWriter2.append(r2DTO.getUsername()+",");
                                outputStreamWriter2.append("未绑定,");
                                outputStreamWriter2.append("未绑定,");
                                outputStreamWriter2.append(r2DTO.getWx_openid()+",");
                                outputStreamWriter2.append("未绑定,");
                                outputStreamWriter2.append("未绑定,");
                                outputStreamWriter2.append(r2DTO.getFaculty_title()+"\n");
                                outputStreamWriter2.close();
                            }

                            //记录登录信息
                            request.getSession().setAttribute("islogin",true);
                            request.getSession().setAttribute("userid",r2DTO.getUsername());
                            response.sendRedirect("http://localhost:8080/PersonInfo.jsp");
                        }
                        EntityUtils.consume(entity3);
                    }

                }else
                {
                    try {
                        response.sendRedirect("https://cas.dgut.edu.cn?appid=javaee");
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }

                EntityUtils.consume(entity2);
        }
        }
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        //到loginservlet的有两种
        //一是mainpage过来的，判断登录状态
        // 未登录，重定向到中央认证
        // 已登录，要退出中央认证

        if(request.getParameter("token")==null) {
            System.out.println("dopost");

            if(request.getSession().getAttribute("islogin")!=null&&request.getSession().getAttribute("islogin").equals("false"))
            {
                //登录
                System.out.println("登录");
                //重定向到中央认证系统
                try {
                    response.sendRedirect("https://cas.dgut.edu.cn?appid=javaee");
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            if(request.getSession().getAttribute("islogin")!=null&&request.getSession().getAttribute("islogin").equals("true"))
            {
                //退出
                System.out.println("退出");
                //向中央认证系统发送登出请求
                request.getSession().setAttribute("islogin","false");
                request.getSession().setAttribute("userid",null);
                request.getSession().invalidate();
                response.sendRedirect("https://cas.dgut.edu.cn/logout?callback=http://localhost:8080/Login.jsp");
            }
        }
    }
}